package com.jgc.daemonthread;

import java.util.concurrent.TimeUnit;

public class DaemonThreadExample {

    public static void main(String[] args) {
        // 创建一个守护线程
        Thread daemonThread = new Thread(() -> {
            while (true) {
                System.out.println("守护线程正在运行...");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        // 设置该线程为守护线程
        daemonThread.setDaemon(true);

        System.out.println("守护线程启动前...");
        daemonThread.start();

        System.out.println("主线程开始执行任务...");
        performMainTask();

        System.out.println("主线程任务执行完毕，即将退出...");
    }

    private static void performMainTask() {
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("主线程任务结束");
    }
}